'use client'
import React, { useRef, useEffect, useState, useCallback } from 'react';

const HeartAnimation = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const [heart, setHeart] = useState<{
    points: Set<string>;
    edgeDiffusionPoints: Set<string>;
    centerDiffusionPoints: Set<string>;
    randomHalo: number;
    generateFrame: number;
  } | null>(null);
  const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
  const [pixelRatio, setPixelRatio] = useState(1);
  const [roses, setRoses] = useState<Array<{
    x: number;
    y: number;
    size: number;
    speed: number;
    rotation: number;
    rotationSpeed: number;
    swingAmplitude: number;
    swingFrequency: number;
    swingPhase: number;
    opacity: number;
    createdAt: number;
  }>>([]);
  const [isMobile, setIsMobile] = useState(false);
  
  // 常量定义
  const ASPECT_RATIO = 4 / 3;
  const IMAGE_ENLARGE = 11;
  const HEART_COLOR = "#FFC0CB";
  const TARGET_FPS = 10;
  const FRAME_INTERVAL = 1000 / TARGET_FPS;
  const ROSE_COUNT = 134;

  // 检测是否为移动设备 - 使用 useCallback 避免重复创建
  const checkIsMobile = useCallback(() => {
    return window.innerWidth < 768;
  }, []);

  // 获取设备像素比
  useEffect(() => {
    setPixelRatio(window.devicePixelRatio || 1);
  }, []);

  // 检测设备类型
  useEffect(() => {
    setIsMobile(checkIsMobile());
    
    const handleResize = () => {
      setIsMobile(checkIsMobile());
    };
    
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [checkIsMobile]);

  // 获取Canvas中心点
  const getCanvasCenter = useCallback(() => {
    return {
      x: dimensions.width / 2,
      y: dimensions.height / 2
    };
  }, [dimensions]);

  // 爱心形状函数
  const heartFunction = useCallback((t: number, shrinkRatio: number = IMAGE_ENLARGE) => {
    if (dimensions.width === 0 || dimensions.height === 0) return [0, 0];
    
    const { x: centerX, y: centerY } = getCanvasCenter();
    const x = 16 * (Math.sin(t) ** 3);
    const y = -(13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t));
    
    const baseScale = isMobile ? 30 : 50;
    const scaleFactor = Math.min(dimensions.width, dimensions.height) / baseScale;
    
    const scaledX = x * shrinkRatio * scaleFactor / 12;
    const scaledY = y * shrinkRatio * scaleFactor / 12;
    
    return [
      scaledX + centerX,
      scaledY + centerY
    ];
  }, [getCanvasCenter, dimensions, isMobile]);

  // 内部散布点
  const scatterInside = useCallback((x: number, y: number, beta: number = 0.15) => {
    const { x: centerX, y: centerY } = getCanvasCenter();
    const ratioX = -beta * Math.log(Math.random());
    const ratioY = -beta * Math.log(Math.random());
    
    const dx = ratioX * (x - centerX);
    const dy = ratioY * (y - centerY);
    
    return [x - dx, y - dy];
  }, [getCanvasCenter]);

  // 收缩函数
  const shrink = useCallback((x: number, y: number, ratio: number) => {
    const { x: centerX, y: centerY } = getCanvasCenter();
    const force = -1 / (((x - centerX) ** 2 + (y - centerY) ** 2) ** 0.6);
    const dx = ratio * force * (x - centerX);
    const dy = ratio * force * (y - centerY);
    return [x - dx, y - dy];
  }, [getCanvasCenter]);

  // 曲线函数
  const curve = useCallback((p: number) => {
    return 2 * (2 * Math.sin(4 * p)) / (2 * Math.PI);
  }, []);

  // 计算位置
  const calcPosition = useCallback((x: number, y: number, ratio: number) => {
    const { x: centerX, y: centerY } = getCanvasCenter();
    const force = 1 / (((x - centerX) ** 2 + (y - centerY) ** 2) ** 0.520);
    const dx = ratio * force * (x - centerX) + (Math.random() * 2 - 1);
    const dy = ratio * force * (y - centerY) + (Math.random() * 2 - 1);
    
    const newX = x - dx;
    const newY = y - dy;
    
    const boundedX = Math.max(0, Math.min(dimensions.width, newX));
    const boundedY = Math.max(0, Math.min(dimensions.height, newY));
    
    return [boundedX, boundedY];
  }, [getCanvasCenter, dimensions]);

  // 创建爱心数据
  const createHeart = useCallback(() => {
    if (dimensions.width === 0 || dimensions.height === 0) return null;
    
    const points = new Set<string>();
    const edgeDiffusionPoints = new Set<string>();
    const centerDiffusionPoints = new Set<string>();
    
    const basePointCount = isMobile ? 800 : 1500;
    const pointCount = Math.floor(basePointCount * (Math.min(dimensions.width, dimensions.height) / 400));
    
    for (let i = 0; i < pointCount; i++) {
      const t = Math.random() * 2 * Math.PI;
      
      const isTip = t < 0.2 || t > 2 * Math.PI - 0.2 || 
                   (t > Math.PI - 0.2 && t < Math.PI + 0.2);
      
      if (isTip && Math.random() > 0.3) {
        continue;
      }
      
      const [x, y] = heartFunction(t);
      
      if (x >= 0 && x <= dimensions.width && y >= 0 && y <= dimensions.height) {
        points.add(`${x},${y}`);
      }
    }
    
    Array.from(points).forEach(point => {
      const [x, y] = point.split(',').map(Number);
      for (let i = 0; i < 2; i++) {
        const [newX, newY] = scatterInside(x, y, 0.05);
        if (newX >= 0 && newX <= dimensions.width && newY >= 0 && newY <= dimensions.height) {
          edgeDiffusionPoints.add(`${newX},${newY}`);
        }
      }
    });
    
    const pointList = Array.from(points);
    const baseCenterPointCount = isMobile ? 1500 : 3000;
    const centerPointCount = Math.floor(baseCenterPointCount * (Math.min(dimensions.width, dimensions.height) / 400));
    
    for (let i = 0; i < centerPointCount; i++) {
      const randomPoint = pointList[Math.floor(Math.random() * pointList.length)];
      const [x, y] = randomPoint.split(',').map(Number);
      const [newX, newY] = scatterInside(x, y, 0.17);
      if (newX >= 0 && newX <= dimensions.width && newY >= 0 && newY <= dimensions.height) {
        centerDiffusionPoints.add(`${newX},${newY}`);
      }
    }
    
    return {
      points,
      edgeDiffusionPoints,
      centerDiffusionPoints,
      randomHalo: isMobile ? 400 : 800,
      generateFrame: 20
    };
  }, [heartFunction, scatterInside, dimensions, isMobile]);

  // 计算帧数据
  const calcFrame = useCallback((heartData: {
    points: Set<string>;
    edgeDiffusionPoints: Set<string>;
    centerDiffusionPoints: Set<string>;
  }, frame: number) => {
    if (!heartData) return [];
    
    const ratio = 10 * curve(frame / 10 * Math.PI);
    const haloRadius = 4 + 6 * (1 + curve(frame / 10 * Math.PI));
    const baseHaloNumber = isMobile ? 1000 : 2000;
    const haloNumber = baseHaloNumber + 3000 * Math.abs(curve(frame / 10 * Math.PI) ** 2);
    
    const allPoints: Array<{ x: number; y: number; size: number }> = [];
    
    const heartHaloPoint = new Set<string>();
    for (let i = 0; i < haloNumber; i++) {
      const t = Math.random() * 2 * Math.PI;
      
      const isTip = t < 0.3 || t > 2 * Math.PI - 0.3 || 
                   (t > Math.PI - 0.3 && t < Math.PI + 0.3);
      
      if (isTip && Math.random() > 0.4) {
        continue;
      }
      
      let [x, y] = heartFunction(t, 11.6);
      [x, y] = shrink(x, y, haloRadius);
      
      if (x >= 0 && x <= dimensions.width && y >= 0 && y <= dimensions.height) {
        const pointKey = `${Math.round(x)},${Math.round(y)}`;
        if (!heartHaloPoint.has(pointKey)) {
          heartHaloPoint.add(pointKey);
          x += (Math.random() * (isMobile ? 12 : 18) - (isMobile ? 6 : 9));
          y += (Math.random() * (isMobile ? 12 : 18) - (isMobile ? 6 : 9));
          
          if (x >= 0 && x <= dimensions.width && y >= 0 && y <= dimensions.height) {
            const size = [1, 1, 2][Math.floor(Math.random() * 3)];
            allPoints.push({ x, y, size });
          }
        }
      }
    }
    
    heartData.points.forEach(point => {
      const [x, y] = point.split(',').map(Number);
      const [newX, newY] = calcPosition(x, y, ratio);
      if (newX >= 0 && newX <= dimensions.width && newY >= 0 && newY <= dimensions.height) {
        const size = Math.floor(Math.random() * 2) + 1;
        allPoints.push({ x: newX, y: newY, size });
      }
    });
    
    heartData.edgeDiffusionPoints.forEach(point => {
      const [x, y] = point.split(',').map(Number);
      const [newX, newY] = calcPosition(x, y, ratio);
      if (newX >= 0 && newX <= dimensions.width && newY >= 0 && newY <= dimensions.height) {
        const size = Math.floor(Math.random() * 2) + 1;
        allPoints.push({ x: newX, y: newY, size });
      }
    });
    
    heartData.centerDiffusionPoints.forEach(point => {
      const [x, y] = point.split(',').map(Number);
      const [newX, newY] = calcPosition(x, y, ratio);
      if (newX >= 0 && newX <= dimensions.width && newY >= 0 && newY <= dimensions.height) {
        const size = Math.floor(Math.random() * 2) + 1;
        allPoints.push({ x: newX, y: newY, size });
      }
    });
    
    return allPoints;
  }, [heartFunction, shrink, curve, calcPosition, dimensions, isMobile]);

  // 绘制文字
  const drawText = useCallback((ctx: CanvasRenderingContext2D) => {
    const { x: centerX, y: centerY } = getCanvasCenter();
    
    const textSize = Math.min(dimensions.width, dimensions.height) / (isMobile ? 10 : 15);
    const lineHeight = textSize * 1.5;
    
    ctx.font = `bold ${textSize}px Arial`;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    
    ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
    ctx.shadowBlur = 10;
    ctx.shadowOffsetX = 2;
    ctx.shadowOffsetY = 2;
    
    ctx.fillStyle = '#FF1493';
    ctx.fillText('袁小倩', centerX, centerY - lineHeight/2);
    ctx.fillText('^七夕快乐^', centerX, centerY + lineHeight/2);
    
    ctx.shadowColor = 'transparent';
    ctx.shadowBlur = 0;
    ctx.shadowOffsetX = 0;
    ctx.shadowOffsetY = 0;
    
    ctx.strokeStyle = '#FFFFFF';
    ctx.lineWidth = 2;
    
    ctx.strokeText('袁小倩', centerX, centerY - lineHeight/2);
    ctx.strokeText('^七夕快乐^', centerX, centerY + lineHeight/2);
  }, [getCanvasCenter, dimensions, isMobile]);

  // 创建玫瑰对象
  const createRose = useCallback(() => {
    const sizeRange = isMobile ? { min: 15, max: 30 } : { min: 20, max: 40 };
    const size = Math.random() * (sizeRange.max - sizeRange.min) + sizeRange.min;
    return {
      x: Math.random() * dimensions.width,
      y: -size,
      size: size,
      speed: Math.random() * 2 + 1,
      rotation: Math.random() * Math.PI * 2,
      rotationSpeed: (Math.random() - 0.5) * 0.05,
      swingAmplitude: Math.random() * 2 + 1,
      swingFrequency: Math.random() * 0.01 + 0.005,
      swingPhase: Math.random() * Math.PI * 2,
      opacity: Math.random() * 0.5 + 0.5,
      createdAt: Date.now()
    };
  }, [dimensions, isMobile]);
  
const drawRose = useCallback((ctx: CanvasRenderingContext2D, rose: {
  x: number;
  y: number;
  size: number;
  rotation: number;
  opacity: number;
}) => {
  ctx.save();
  ctx.translate(rose.x, rose.y);
  ctx.rotate(rose.rotation);
  ctx.globalAlpha = rose.opacity;
  
  const { size } = rose;
  
  // 绘制茎
  ctx.strokeStyle = '#2E8B57';
  ctx.lineWidth = size * 0.05;
  ctx.lineCap = 'round';
  
  // 茎的渐变
  const stemGradient = ctx.createLinearGradient(0, 0, 0, size * 1.5);
  stemGradient.addColorStop(0, '#32CD32'); // 浅绿色
  stemGradient.addColorStop(1, '#2E8B57'); // 深绿色
  
  ctx.strokeStyle = stemGradient;
  ctx.beginPath();
  ctx.moveTo(0, size * 0.3);
  // 让茎稍微弯曲
  ctx.quadraticCurveTo(size * 0.2, size * 0.8, 0, size * 1.5);
  ctx.stroke();
  
  // 绘制叶子
  ctx.fillStyle = '#228B22';
  ctx.strokeStyle = '#2E8B57';
  ctx.lineWidth = size * 0.02;
  
  // 第一片叶子
  ctx.save();
  ctx.translate(size * 0.15, size * 0.8);
  ctx.rotate(-Math.PI / 6);
  drawLeaf(ctx, size * 0.3);
  ctx.restore();
  
  // 第二片叶子
  ctx.save();
  ctx.translate(-size * 0.15, size * 1.0);
  ctx.rotate(Math.PI / 6);
  drawLeaf(ctx, size * 0.25);
  ctx.restore();
  
  // 绘制玫瑰花蕾
  drawRoseBud(ctx, size);
  
  ctx.restore();
}, []);

// 绘制叶子辅助函数
const drawLeaf = (ctx: CanvasRenderingContext2D, size: number) => {
  // 叶子渐变
  const leafGradient = ctx.createLinearGradient(0, -size/2, 0, size/2);
  leafGradient.addColorStop(0, '#32CD32'); // 浅绿色
  leafGradient.addColorStop(1, '#228B22'); // 深绿色
  
  ctx.fillStyle = leafGradient;
  ctx.strokeStyle = '#2E8B57';
  ctx.lineWidth = size * 0.05;
  
  // 绘制叶子形状
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.quadraticCurveTo(size * 0.5, -size * 0.3, size * 0.7, 0);
  ctx.quadraticCurveTo(size * 0.5, size * 0.3, 0, 0);
  ctx.fill();
  ctx.stroke();
  
  // 绘制叶脉
  ctx.strokeStyle = '#2E8B57';
  ctx.lineWidth = size * 0.02;
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.lineTo(size * 0.7, 0);
  ctx.stroke();
  
  ctx.beginPath();
  ctx.moveTo(size * 0.2, 0);
  ctx.quadraticCurveTo(size * 0.35, -size * 0.15, size * 0.5, -size * 0.1);
  ctx.stroke();
  
  ctx.beginPath();
  ctx.moveTo(size * 0.2, 0);
  ctx.quadraticCurveTo(size * 0.35, size * 0.15, size * 0.5, size * 0.1);
  ctx.stroke();
};

// 绘制玫瑰花蕾
const drawRoseBud = (ctx: CanvasRenderingContext2D, size: number) => {
  // 花蕾基础位置
  const centerX = 0;
  const centerY = 0;
  
  // 花瓣颜色渐变 - 从深粉到浅粉
  const petalGradient = ctx.createRadialGradient(
    centerX, centerY, size * 0.1,
    centerX, centerY, size * 0.5
  );
  petalGradient.addColorStop(0, '#FF69B4'); // 中心较深
  petalGradient.addColorStop(1, '#FFB6C1'); // 边缘较浅
  
  ctx.fillStyle = petalGradient;
  ctx.strokeStyle = '#FF1493';
  ctx.lineWidth = size * 0.03;
  
  // 绘制外层花瓣 (5片)
  for (let i = 0; i < 7; i++) {
    const angle = (i / 7) * Math.PI * 2;
    const petalSize = size * (0.5 + Math.sin(angle) * 0.1);
    
    ctx.save();
    ctx.rotate(angle);
    
    // 外层花瓣稍微展开
    const openness = 0.7 + Math.sin(angle) * 0.2;
    
    ctx.beginPath();
    ctx.ellipse(
      size * 0.3 * openness, 
      0, 
      petalSize * 0.6, 
      petalSize * 0.8, 
      angle * 0.5, 
      0, 
      Math.PI * 2
    );
    ctx.fill();
    ctx.stroke();
    
    ctx.restore();
  }
  
  // 绘制中层花瓣 (4片) - 稍微小一些
  for (let i = 0; i < 4; i++) {
    const angle = (i / 4) * Math.PI * 2 + Math.PI/8;
    const petalSize = size * (0.4 + Math.cos(angle) * 0.05);
    
    ctx.save();
    ctx.rotate(angle);
    
    ctx.beginPath();
    ctx.ellipse(
      size * 0.15, 
      0, 
      petalSize * 0.5, 
      petalSize * 0.7, 
      angle * 0.3, 
      0, 
      Math.PI * 2
    );
    ctx.fill();
    ctx.stroke();
    
    ctx.restore();
  }
  
  // 绘制内层花瓣 (3片) - 最小
  for (let i = 0; i < 3; i++) {
    const angle = (i / 3) * Math.PI * 2 + Math.PI/6;
    const petalSize = size * 0.3;
    
    ctx.save();
    ctx.rotate(angle);
    
    ctx.beginPath();
    ctx.ellipse(
      size * 0.05, 
      0, 
      petalSize * 0.4, 
      petalSize * 0.6, 
      angle * 0.2, 
      0, 
      Math.PI * 2
    );
    ctx.fill();
    ctx.stroke();
    
    ctx.restore();
  }
  
  // 绘制花蕊
  ctx.fillStyle = '#FFFF00';
  ctx.beginPath();
  ctx.arc(centerX, centerY, size * 0.1, 0, Math.PI * 2);
  ctx.fill();
  
  // 绘制花蕊细节
  ctx.strokeStyle = '#FFD700';
  ctx.lineWidth = size * 0.01;
  for (let i = 0; i < 8; i++) {
    const angle = (i / 8) * Math.PI * 2;
    ctx.beginPath();
    ctx.moveTo(centerX, centerY);
    ctx.lineTo(
      centerX + Math.cos(angle) * size * 0.15,
      centerY + Math.sin(angle) * size * 0.15
    );
    ctx.stroke();
  }
};
  

  // 更新玫瑰位置
  const updateRoses = useCallback(() => {
    setRoses(prevRoses => {
      let updatedRoses = prevRoses.filter(rose => rose.y < dimensions.height + rose.size);
      
      while (updatedRoses.length < ROSE_COUNT) {
        updatedRoses.push(createRose());
      }
      
      const currentTime = Date.now();
      return updatedRoses.map(rose => {
        const time = currentTime * 0.001;
        const age = (currentTime - rose.createdAt) / 1000;
        
        const speedMultiplier = 1 + age * 0.01;
        const amplitudeMultiplier = 1 + age * 0.005;
        
        return {
          ...rose,
          y: rose.y + rose.speed * speedMultiplier,
          x: rose.x + Math.sin(time * rose.swingFrequency + rose.swingPhase) * rose.swingAmplitude * amplitudeMultiplier,
          rotation: rose.rotation + rose.rotationSpeed
        };
      });
    });
  }, [dimensions, createRose, ROSE_COUNT]);

  // 处理窗口大小变化
  useEffect(() => {
    let resizeTimeout: NodeJS.Timeout;
    
    const updateDimensions = () => {
      if (containerRef.current) {
        const { width, height } = containerRef.current.getBoundingClientRect();
        const mobileAspectRatio = isMobile ? 3/4 : ASPECT_RATIO;
        const newWidth = isMobile ? width : Math.min(width, height * mobileAspectRatio);
        const newHeight = newWidth / mobileAspectRatio;
        
        setDimensions({ width: newWidth, height: newHeight });
      }
    };

    const debouncedUpdate = () => {
      clearTimeout(resizeTimeout);
      resizeTimeout = setTimeout(updateDimensions, 250);
    };

    updateDimensions();

    window.addEventListener('resize', debouncedUpdate);
    return () => {
      window.removeEventListener('resize', debouncedUpdate);
      clearTimeout(resizeTimeout);
    };
  }, [isMobile]);

  // 初始化爱心数据
  useEffect(() => {
    if (dimensions.width > 0 && dimensions.height > 0 && isMobile) {
      const newHeart = createHeart();
      setHeart(newHeart);
    }
  }, [createHeart, dimensions, isMobile]);

  // 初始化玫瑰
  useEffect(() => {
    if (dimensions.width > 0 && dimensions.height > 0 && isMobile) {
      const initialRoses = [];
      for (let i = 0; i < ROSE_COUNT; i++) {
        initialRoses.push(createRose());
      }
      setRoses(initialRoses);
    }
  }, [createRose, dimensions, isMobile, ROSE_COUNT]);

  // 玫瑰更新间隔
  useEffect(() => {
    if (!isMobile) return;
    
    let lastTime = 0;
    let animationFrameId: number;
    
    const updateRosesLoop = (timestamp: number) => {
      if (timestamp - lastTime > FRAME_INTERVAL) {
        updateRoses();
        lastTime = timestamp;
      }
      animationFrameId = requestAnimationFrame(updateRosesLoop);
    };
    
    animationFrameId = requestAnimationFrame(updateRosesLoop);
    
    return () => {
      cancelAnimationFrame(animationFrameId);
    };
  }, [updateRoses, isMobile, FRAME_INTERVAL]);

  // 动画循环
  useEffect(() => {
    if (!heart || dimensions.width === 0 || dimensions.height === 0 || !isMobile) return;
    
    const canvas = canvasRef.current;
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    
    canvas.width = dimensions.width * pixelRatio;
    canvas.height = dimensions.height * pixelRatio;
    
    canvas.style.width = `${dimensions.width}px`;
    canvas.style.height = `${dimensions.height}px`;
    
    ctx.scale(pixelRatio, pixelRatio);
    
    let animationFrameId: number;
    let frame = 0;
    let lastTime = 0;
    
    const render = (timestamp: number) => {
      if (timestamp - lastTime < FRAME_INTERVAL) {
        animationFrameId = requestAnimationFrame(render);
        return;
      }
      
      lastTime = timestamp;
      
      // 绘制渐变背景
      const gradient = ctx.createLinearGradient(0, 0, 0, dimensions.height);
      gradient.addColorStop(0, '#1a0033'); // 深紫色
      gradient.addColorStop(0.5, '#330066'); // 中等紫色
      gradient.addColorStop(1, '#4d0099'); // 浅紫色
      
      ctx.fillStyle = gradient;
      ctx.fillRect(0, 0, dimensions.width, dimensions.height);
      
      const time = Date.now() * 0.001;
      roses.forEach(rose => {
        drawRose(ctx, rose);
      });
      
      const points = calcFrame(heart, frame % 20);
      
      points.forEach(point => {
        ctx.fillStyle = HEART_COLOR;
        const adjustedSize = Math.max(1, point.size * (pixelRatio > 1.5 ? 1.5 : 1));
        ctx.fillRect(point.x, point.y, adjustedSize, adjustedSize);
      });
      
      drawText(ctx);
      
      frame++;
      animationFrameId = requestAnimationFrame(render);
    };
    
    animationFrameId = requestAnimationFrame(render);
    
    return () => {
      cancelAnimationFrame(animationFrameId);
    };
  }, [heart, calcFrame, dimensions, drawText, roses, drawRose, pixelRatio, isMobile, FRAME_INTERVAL]);

  // 如果不是移动设备，不渲染任何内容
  if (!isMobile) {
    return null;
  }

  return (
    <div ref={containerRef} className="heart-container" style={{ 
      width: '100%', 
      height: '100vh',
      background: 'linear-gradient(to bottom, #1a0033, #4d0099)',
      overflow: 'hidden'
    }}>
      <canvas
        ref={canvasRef}
        className="heart-canvas"
      />
    </div>
  );
};

export default HeartAnimation;